﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.Framework.Client;
using System.ComponentModel;

namespace FunctionPoint.Common
{
    public class TfsUserGroup : TfsSecurityObject, INotifyPropertyChanged
    {
        public SortedSet<TfsUser> Members
        {
            get;
            private set;
        }
        public Identity Identity
        {
            get;
            private set;
        }

        public TeamFoundationIdentity TeamFoundationIdentity
        {
            get;
            private set;
        }
        public IGroupSecurityService2 GroupSecurityService
        {
            get;
            private set;
        }
        public string DisplayName
        {
            get
            {
                return TeamFoundationIdentity.DisplayName;
            }
        }

        public TfsUserGroup(Identity identity, IGroupSecurityService2 groupSecurityService, bool loadUsers = false)
        {
            Members = new SortedSet<TfsUser>();
            GroupSecurityService = groupSecurityService;
            Identity = groupSecurityService.ReadIdentity(SearchFactor.Sid, identity.Sid, QueryMembership.Expanded);
            TeamFoundationIdentity = GroupSecurityService.Convert(identity);

            if (loadUsers && Identity.Members != null && Identity.Members.Length > 0)
            {
                var identityList = GroupSecurityService.ReadIdentities(SearchFactor.Sid, Identity.Members, QueryMembership.Expanded);
                identityList.ToList().ForEach(currentIdentity =>
                {
                    TfsUser user = new TfsUser(currentIdentity, groupSecurityService);
                    Members.Add(user);
                });

                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Members"));
            }
        }



        public event PropertyChangedEventHandler PropertyChanged;
    }
}
